java


Control Statements in Java: if, else, and switch

Control statements allow your program to make decisions and execute certain blocks of code depending on conditions. In Java, some of the most common decision-making statements are: if if-else if-else if ladder switch Let’s explore each with examples. The if Statement The if statement executes a block of code only if the given condition is true. Syntax: if (condition) { // Code to execute if condition is true } Example: int age = 20; if (age >= 18) { System.out.println("You are eligible to vote."); } How it works: If age >= 18 is true, the message is printed. If false, the program simply skips the block.

if (condition) {
    // Runs if condition is true
} else {
    // Runs if condition is false
}


int number = 5;

if (number % 2 == 0) {
    System.out.println("Even number");
} else {
    System.out.println("Odd number");
} 

if-else if

if (condition1) { // Runs if condition1 is true } else if (condition2) { // Runs if condition2 is true } else { // Runs if none of the conditions are true }

int marks = 85;

if (marks >= 90) {
    System.out.println("Grade A+");
} else if (marks >= 75) {
    System.out.println("Grade A");
} else if (marks >= 50) {
    System.out.println("Grade B");
} else {
    System.out.println("Fail");
} 

The switch Statement

switch is used when you have multiple possible values for a single variable and you want to execute different code for each value.

switch (expression) {
    case value1:
        // Code for value1
        break;
    case value2:
        // Code for value2
        break;
    default:
        // Code if none of the cases match
}



int day = 3;
String dayName;

switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
   break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    case 6:
        dayName = "Saturday";
        break;
    case 7:
        dayName = "Sunday";
        break;
    default:
        dayName = "Invalid day";
}

System.out.println(dayName); 

Conclusion

Use if / if-else when you have conditions involving ranges or complex expressions. Use switch when checking against multiple fixed values for the same variable. Both are essential for decision-making in Java programs.